<template>
    <div>
        <toolbar :source="toolbars"></toolbar>
        <base-table
            ref="table"
            v-model="pellets"
            :column="column"
            @selection-change="onSelectionChange"
        ></base-table>
    </div>
</template>

<script setup>
import { BaseTable, Toolbar } from "@/components";
import { getPellet, savePellets } from "@/api/pellet";
import useRedo from "@/hooks/useRedo";
import { ref } from "vue";

const column = ref([
    {
        type: "selection",
    },
    {
        type: "index",
    },
    {
        prop: "name",
        label: "名称",
    },
    {
        prop: "grade",
        label: "等级",
    },
    {
        prop: "effect",
        label: "概率",
    },
]);
let pellets = ref([]);
let toolbars = ref([]);
let selection = ref([]);
const { undoBtn, redoBtn } = useRedo(pellets);
const table = ref(null);
const saveBtn = {
    key: "save",
    label: "保存",
    type: "primary",
    onclick() {
        submit();
    },
};
const addBtn = {
    key: "add",
    label: "新增",
    onclick(e) {
        table.value.addRow(e);
    },
};
const deleteBtn = {
    key: "delete",
    label: "删除",
    type: "danger",
    onclick() {
        deleteSource();
    },
};
getPellet().then((data) => {
    pellets.value = data;
});

watchEffect(() => {
    toolbars.value = selection.value?.length
        ? [saveBtn, addBtn, undoBtn, redoBtn, deleteBtn]
        : [saveBtn, addBtn, undoBtn, redoBtn];
});

function onSelectionChange(val) {
    selection.value = val;
}
function deleteSource() {
    const map = new Map();
    selection.value.forEach((item) => map.set(item, true));
    pellets.value = pellets.value.filter((item) => !map.has(item));
    selection.value = selection.value.filter((item) => !map.has(item));
    map.clear();
}
function submit() {
    savePellets(pellets.value);
}
</script>

<style></style>
